package cn.maihe.elg.operation.utils;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author WJH
 * @Date 2020/11/09
 */
@Slf4j
public class ValidateUtil {

    private final static Validator validator;

    static {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
                .failFast(true).buildValidatorFactory();
        validator = validatorFactory.getValidator();
    }

    /**
     * @param paramObj 级联校验则 级联对象@Valid
     * @param <T>
     */
    public static <T> void validate(T paramObj) {
        if (paramObj == null) {
            throw new RuntimeException("参数对象不能为空");
        }
        Set<ConstraintViolation<T>> set = null;
        try {
            set = ValidateUtil.validator.validate(paramObj);
        } catch (Exception e) {
            throw new RuntimeException("参数校验异常：" + e.getMessage(), e);

        }
        if (set != null && !set.isEmpty()) {
            String errorMsg = set.stream().map(cv -> String.format("[%s]%s,当前值为[%s]", cv.getPropertyPath(), cv.getMessage(), cv.getInvalidValue())).collect(Collectors.joining(";"));
            throw new RuntimeException(errorMsg);
        }
    }

    public static void main(String[] args) {
        Path p = Paths.get("c:\\ofd", "tmp/test.pdf");
        System.out.println("p = " + p.toString());
    }

}
